package com.joymart.qualification.service;

import com.joymart.common.system.BusinessConfig;
import com.joymart.common.utils.SecurityUtils;
import com.joymart.compute.service.VitalityPointService;
import com.joymart.qualification.model.ShopEvaluation;
import com.joymart.user.model.BusinessRole;
import com.joymart.user.model.CachedUser;
import com.joymart.user.service.UserCacheManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.MathContext;
import java.util.Optional;

@Service
public class ShopEvaluationService {

    @Autowired
    private VitalityPointService vitalityPointService;
    @Autowired
    private UserCacheManager userCacheManager;
    @Autowired
    private BusinessConfig businessConfig;

    public ShopEvaluation evaluateShop(String userId){
        CachedUser user = userCacheManager.get(userId);
        BigDecimal points = vitalityPointService.sumUserVitalityPoints(
                SecurityUtils.getCurrentUserId());
        boolean hasShopChild = Optional.ofNullable(
                        userCacheManager.downwardsSearchUntil(user, c -> c.getBusinessRoles().contains(BusinessRole.AG_SHOP)))
                .isPresent();
        BigDecimal pointsRequired =  hasShopChild?
                businessConfig.getShopQualificationPoints().divide(BigDecimal.valueOf(2), MathContext.DECIMAL64)
                :businessConfig.getShopQualificationPoints();
        return new ShopEvaluation(points, pointsRequired);
    }



}
